package com.iengoo.inductionms.ctrl.web;

import com.iengoo.inductionms.common.SimpleToken;
import com.iengoo.inductionms.entity.Employee;
import com.iengoo.inductionms.entity.User;
import com.iengoo.inductionms.exception.LoginException;
import com.iengoo.inductionms.service.LoginService;
import com.iengoo.inductionms.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-03-07 22:33
 */
@Controller
public class LoginController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private LoginService loginService;
    Map<String, Object> r = new HashMap<>();

    @GetMapping("/login")
    public String loginPage() {
        return "login.html";
    }

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestBody Employee employee, HttpServletRequest req) {
        r.clear();

        try {
            User login = loginService.Login(employee);
            r.put("data", login);
            r.put("code", 200);
            req.getSession().setAttribute("USER", login);
        } catch (LoginException e) {
            r.put("msg", e.getMessage());
            r.put("code", -500);
        }


        return r;
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest req) {
        // 注销用户，使session失效。
        req.getSession().invalidate();
        return "redirect:/login.html";
    }
//    @CrossOrigin(origins = "http://192.168.123.131:8080", maxAge = 3600)
    @PostMapping("/mobile/login")
    @ResponseBody
    public Map<String, Object> mobileLogin(@RequestBody Employee employee, HttpServletRequest req) {
        r.clear();

        try {
            User login = loginService.Login(employee);
            String token = SimpleToken.create();
            tokenService.insert(token);
            login.setToken(token);
            r.put("data", login);
            r.put("code", 200);
            req.getSession().setAttribute("USER", login);
        } catch (LoginException e) {
            r.put("msg", e.getMessage());
            r.put("code", -500);
        }


        return r;
    }
}
